<?php
namespace app\api\logic;

use app\common\logic\Base;
use think\facade\Request;

class Url extends  Base {
    
    /**
     * @desc 创建url链接
     * @param array $params
     * @param int $userId
     * @return array|bool
     * @throws \Exception
     */
    public function build($params, $userId)
    {
        $request   = Request::instance();
        $ip        = $request->ip(); //获取客户端IP地址
        $header    = $request->header();
        $userAgent = $header['user-agent'];
        
        $keyword = model('Url')->getUrlKeyword(8);
        if($params['expireTime']) {
            $expireTime = date('Y-m-d H:i:s', $params['expireTime']);
        }else {
            $expireTime = date('Y-m-d H:i:s', strtotime('+20year'));
        }
        $data    = [
            'user_id'     => $userId,
            'link'        => $params['link'],
            'keyword'     => $keyword,
            'user_agent'  => $userAgent,
            'ip'          => $ip,
            'expire_time' => $expireTime,
            'password'    => $params['password'],
            'remark'      => $params['remark'],
            'modify_time' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s')
        ];
        $urlId   = model('Url')->insertGetId($data);
        if ($urlId === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
        
        //获取用户配置的域名
        $domainUrl = model('Domain')->getDomain($userId);
        
        return [
            'keyword'  => $keyword,
            'shortUrl' => $domainUrl . '/' . $keyword,
            'link'     => $params['link'],
        ];
    }
    
}
